﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Orm.DataEntity;

namespace LiMinCRMPlugin
{
    /// <summary>
    /// 销售订单变更插件
    /// </summary>
    /// <remarks>
    /// 功能：销售订单变更插件
    /// 创建人：wzx
    /// 创建日期：2024.8.1
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    /// 
    [Description("销售订单变更保存校验")]
    [HotUpdate]
    public class SalesOrderChangeVerification : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            //编码
            e.FieldKeys.Add("FBillNo");
            //CRM编码
            e.FieldKeys.Add("F_DEV_CRMNumber");
            //CRM唯一ID
            e.FieldKeys.Add("F_DEV_CRMId");
            e.FieldKeys.Add("F_DEV_DataSrc");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);

            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (ExtendedDataEntity extended in e.SelectedRows)
            {

                DynamicObject dy = extended.DataEntity;


                string DataSrc = dy["F_DEV_DataSrc"].ToString();//数据来源

                if (DataSrc == "CRM")
                {

                    string CRMNumber = Convert.ToString(dy["F_DEV_CRMNumber"]);//CRM编码
                    string CRMId = Convert.ToString(dy["F_DEV_CRMId"]);//CRM唯一id
                    if (CRMId != "" && CRMId != " ")
                    {
                        string sql = @"/*SELECT *
FROM [CRM].[ecology].[dbo].uf_jch_fhtzd where ddbh='" + CRMId + "')";
                        DataTable dt = DBUtils.ExecuteDataSet(Context, sql).Tables[0];
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            if (Convert.ToInt32(dt.Rows[0][0]) > 0)
                            {


                                throw new KDException("禁止变更保存", "CRM订单已创建发货通知单，不允许变更！");
                            }
                        }
                    }


                }



            }
        }
    }
}
